#include "sql_compiler_cpp/Lexer.h"
#include "sql_compiler_cpp/Parser.h"
#include "sql_compiler_cpp/ExecutionPlan.h"
#include <iostream>

using namespace MiniDB;

/**
 * 演示谓词下推优化器的实际效果
 */
int main() {
    std::cout << "🎯 SQL编译器谓词下推优化演示" << std::endl;
    std::cout << std::string(50, '=') << std::endl;

    // 示例SQL查询
    std::string sql = "SELECT id, name, age FROM users WHERE age >= 18 AND department = 'Engineering' AND salary > 50000;";

    std::cout << "📝 测试查询: " << sql << std::endl;
    std::cout << std::endl;

    // 词法和语法分析
    Lexer lexer(sql);
    auto tokens = lexer.tokenize();

    Parser parser(tokens);
    auto statements = parser.parse();

    if (statements.empty()) {
        std::cerr << "❌ 解析失败" << std::endl;
        return 1;
    }

    // 创建符号表
    SymbolTable symbol_table;
    TableInfo users_table("users");

    // 添加列定义
    ColumnInfo id_col("id", DataType::INT, 0, false, true);
    ColumnInfo name_col("name", DataType::VARCHAR, 50, false, false);
    ColumnInfo age_col("age", DataType::INT, 0, true, false);
    ColumnInfo dept_col("department", DataType::VARCHAR, 30, true, false);
    ColumnInfo salary_col("salary", DataType::INT, 0, true, false);

    users_table.addColumn(id_col);
    users_table.addColumn(name_col);
    users_table.addColumn(age_col);
    users_table.addColumn(dept_col);
    users_table.addColumn(salary_col);

    symbol_table.addTable(users_table);

    // 生成执行计划（带优化）
    PlanGenerator plan_generator(symbol_table);
    plan_generator.enablePredicatePushdown(true);

    std::cout << "⚡ 生成优化后的执行计划..." << std::endl;
    auto optimized_plan = plan_generator.generatePlan(statements);

    std::cout << "\n📋 优化后的执行计划:" << std::endl;
    optimized_plan->print();

    // 对比：不使用优化
    plan_generator.enablePredicatePushdown(false);
    auto unoptimized_plan = plan_generator.generatePlan(statements);

    std::cout << "\n📋 未优化的执行计划（对比）:" << std::endl;
    unoptimized_plan->print();

    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << "✨ 谓词下推优化效果总结:" << std::endl;
    std::cout << "• 过滤条件被推到扫描算子层面" << std::endl;
    std::cout << "• 减少了需要处理的数据量" << std::endl;
    std::cout << "• 提高了查询执行效率" << std::endl;
    std::cout << "• 支持复杂AND表达式的分解和下推" << std::endl;

    return 0;
}
